import { Component, OnInit, Inject } from '@angular/core';
import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common';
import { Router, ActivatedRoute, Params } from '@angular/router';

import { Auth } from '../domain/auth';

declare var $: any;
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  username = '';
  password = '';
  auth: Auth;

  constructor(@Inject('auth') private service, private router: Router, private location: Location) { }
  ngOnInit(): void {
  }
  onSubmit(formValue) {
    this.service
      .loginWithCredentials(formValue.login.username, formValue.login.password)
      .then(auth => {
        const redirectUrl = (auth.redirectUrl === null) ? '/' : auth.redirectUrl;
        if (!auth.hasError) {
          this.router.navigate([redirectUrl]);
          localStorage.removeItem('redirectUrl');
          this.router.navigate(['/checktable']);

        } else {
          this.auth = Object.assign({}, auth);
          alert('密码错误');
        }
      });
  }
  gologin():void {
    $.ajax({
      type: 'GET',
      url: 'http://localhost:3000/staffs',
      dataType: 'json',
      data : {
        "account": (document.getElementsByName('username')[0] as HTMLInputElement).value,
      },
      success: function (data) {
        if (data.length > 0) {
          $.ajax({
            type: 'post',
            url: 'http://localhost:3000/login',
            data: {
              "name": data[0].name,
              "position": data[0].position,
              "department": data[0].department,
              "account": data[0].account,
              "password": data[0].password
            },
          });
      }
      }
    });
  }
}
